package com.stephen.bp.model;

import java.util.HashMap;

import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.log4j.Log4j2;

/**
 * @author Qiuww
 */
@Log4j2
public class UserChannel {
    public static HashMap<String, Channel> channelHashMap = new HashMap<>();

    public static void writeAndFlush0(String username, RequestAndResponse requestAndResponse) {
        Channel channel = channelHashMap.get(username);
        String jsonString = JSONObject.toJSONString(requestAndResponse);
        if (channel == null || !channel.isActive()) {
            log.warn("用户连接已经断开:{}, 丢失消息:{}", username, jsonString);
            return;
        }
        try {
            channel.writeAndFlush(new TextWebSocketFrame(jsonString)).addListener(future -> {
                if (!future.isSuccess()) {
                    Throwable cause = future.cause();
                    if (cause != null) {
                        log.error("发送消息失败,用户:{}, 丢失消息:{}, 原因:{}", username, jsonString, cause.getMessage());
                    }
                } else {
                    if (requestAndResponse.getAction().equals(Action.TIME)) {
                        //只输出每隔10秒或者最后三秒的日志，避免刷屏
                        long time = Long.parseLong(requestAndResponse.content);
                        if (time % 10 == 0 || time <= 3) {
                            log.info("回复用户:{},回复内容:{}", username, jsonString);
                        }
                    } else {
                        log.info("回复用户:{},回复内容:{}", username, jsonString);
                    }
                }
            });
        } catch (Exception e) {
            log.error("发送消息失败,用户:{},丢失消息:{}, 原因:{}", username, jsonString, e.getMessage());
        }
    }

    public static Channel getChannelByUsername(String username) {
        return channelHashMap.get(username);
    }

    public static void kick(String username) {
        RequestAndResponse requestAndResponse = new RequestAndResponse();
        requestAndResponse.setAction(Action.KICK);
        writeAndFlush0(username, requestAndResponse);
    }

    public static void updateChannel(String username, Channel channel) {
        channelHashMap.put(username, channel);
    }

    public static String getUserNameByChannel(Channel channel) {
        for (String username : channelHashMap.keySet()) {
            Channel storedChannel = channelHashMap.get(username);
            if (storedChannel == channel) {
                return username;
            }
        }
        return null; // 如果找不到对应的用户名，则返回 null
    }

    public static void notStart(String username) {
        RequestAndResponse requestAndResponse = new RequestAndResponse();
        requestAndResponse.setAction(Action.NOT_START);
        writeAndFlush0(username, requestAndResponse);
    }
}
